package cn.icanci.ladybird.common.util;

import cn.icanci.ladybird.pojo.entity.Admin;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

/**
 * @author: icanci
 * @date: Created in 2020/9/29 15:00
 * @classAction: JWT 工具类
 * -
 * 注意点：
 * - 生成的token 可以通过base64进程解密出明文信息
 * - base64进行解密出明文信息，修改在进行编码。会解密失败
 * - 无法作废已经颁布的token 除非改密钥
 */
@SuppressWarnings("all")
public class JWTUtils {
    /**
     * 过期时间 1周
     */
    private static final long EXPIRE = 60000 * 60 * 24 * 7;
    /**
     * 密钥
     */
    private static final String SECRET = "ladybird.icanci.cn";

    /**
     * 令牌前缀
     */
    private static final String TOKEN_PREFIX = "icanci.cn";

    /**
     * subject 主题
     */
    private static final String SUBJECT = "icanci.cn";

    /**
     * 根据用户信息生成令牌
     *
     * @param user
     * @return 返回token
     */

    public static String generateAdminJWTWebToken(Admin admin) {
        String token = Jwts.builder()
                .setSubject(SUBJECT)
                .claim("admin_head_img", admin.getAdminHeadImg())
                .claim("admin_id", admin.getAdminId())
                .claim("admin_enabled", admin.getAdminEnabled())
                .claim("admin_name", admin.getAdminUsername())
                .claim("admin_authority", admin.getAuthority())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, SECRET).compact();
        token = TOKEN_PREFIX + token;
        return token;
    }


    /**
     * 检验的方法
     *
     * @param token token
     * @return 返回 Claims
     */
    public static Claims checkJWT(String token) {
        try {
            final Claims claims = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                    .getBody();
            return claims;
        } catch (Exception e) {
            return null;
        }
    }
}
